#!/bin/bash
#
# Compile ADVRP and create a user and group called 'advrp' for privilege
# dropping.

EXTRA_CFLAGS=""

# Compile and link
echo '/*'
echo ' * Compiling advrp.'
gcc $EXTRA_CFLAGS -o advrp advrp.c debug.c hash.c holddown.c init.c kroute.c receiver.c sender.c verify.c -lpthread -g

# Check gcc's exit status
ret=$?
if [[ $ret -ne 0 ]] ; then
	echo ' * GCC returned '$ret', which may be a problem. Look through the'
	echo ' * above output for error messages.'
	echo ' */'
	exit $ret
fi

# Create user "advrp" so the program can drop privileges (you can specify
# a different user with the -p flag to advrp)
echo ' * Checking for user advrp...'
if grep advrp /etc/passwd 1> /dev/null ; then 
	echo ' * User advrp found.'
else
	echo ' * User advrp not found. Attempting to create it...'
	if [[ `id -u` -ne 0 ]] ; then
		sudo useradd advrp
		if [[ $? -ne 0 ]] ; then
			echo ' * There was a problem creating the advrp user.'
			echo ' */'
			exit 1
		else
			echo ' * Successfully created user.'
		fi
	else
		useradd advrp
		if [[ $? -ne 0 ]] ; then
			echo ' * There was a problem creating the advrp user.'
			echo ' */'
			exit 1
		else
			echo ' * Successfully created user.'
		fi
		
	fi
fi

# Make sure the "advrp" group exists; normally useradd will create it, but
# in case it was added in a different manner...
echo ' * Checking for group advrp...'
if grep advrp /etc/group 1> /dev/null ; then 
	echo ' * Group advrp found.'
else
	echo ' * Group advrp not found. Attempting to create it...'
	if [[ `id -u` -ne 0 ]] ; then
		sudo groupadd advrp
		if [[ $? -ne 0 ]] ; then
			echo ' * There was a problem creating the advrp group.'
			echo ' */'
			exit 1
		else
			echo ' * Successfully created group.'
		fi
	else
		groupadd advrp
		if [[ $? -ne 0 ]] ; then
			echo ' * There was a problem creating the advrp group.'
			echo ' */'
			exit 1
		else
			echo ' * Successfully created group.'
		fi
		
	fi
fi

echo ' * Finished.'
echo ' */'
exit 0
